﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Collections;
using WatchSeriesHelper.Entities;
using EricUtility;
using System.Windows.Forms;

namespace WatchSeriesHelper.Persistance
{
    public static class PersistFavs
    {
        private static readonly string newBeginning = "|TVSHOW|";
        private static readonly string oldFilename = "favs.txt";
        private static readonly string filename = "favsTVShows.txt";
        public static List<TVShowInfo> LoadFavShows()
        {
            List<TVShowInfo> result = new List<TVShowInfo>();
            if (File.Exists(oldFilename))
            {
                File.Move(oldFilename, filename);
            }
            if (File.Exists(filename))
            {
                StreamReader sr = new StreamReader(filename);
                while (!sr.EndOfStream)
                {
                    string line = sr.ReadLine();
                    string[] split = line.Split(';');
                    if (split[0] != newBeginning)
                    {
                        if (split.Length == 2)
                            result.Add(new TVShowInfo(split[0], split[1]));
                        else if (split.Length == 3)
                            result.Add(new TVShowInfo(split[0], split[1], split[2]));
                        else if (split.Length == 4)
                            result.Add(new TVShowInfo(split[0], split[1], split[2], split[3]));
                        else if (split.Length == 5)
                            result.Add(new TVShowInfo(split[0], split[1], split[2], split[3], split[4]));
                        else
                            result.Add(new TVShowInfo(split[0], split[1], split[2], split[3], split[4], bool.Parse(split[5]), split[6], split[7]));
                    }
                    else
                    {
                        StringTokenizer token = new StringTokenizer(line, ';');
                        token.NextToken();
                        int v = int.Parse(token.NextToken());
                        string id = token.NextToken();
                        string name = token.NextToken();
                        string lastSeasonViewed = token.NextToken();
                        string lastEpisodViewed = token.NextToken();
                        string epGuideId = token.NextToken();
                        bool epGuideLoaded = bool.Parse(token.NextToken());
                        string tvRageId = null;
                        string imdbId = null;
                        bool rageBroken = false;
                        if (epGuideLoaded)
                        {
                            imdbId = token.NextToken();
                            tvRageId = token.NextToken();
                            if (tvRageId == false.ToString())
                                rageBroken = true;
                        }

                        // LOAD TV RAGE
                        TvRageEntry rage = null;
                        if (v >= 1 && !rageBroken)
                        {
                            if (epGuideLoaded && epGuideId != TVShowInfo.NO_EPGUIDE)
                            {
                                bool rageLoaded = bool.Parse(token.NextToken());
                                if (rageLoaded)
                                {
                                    bool running = bool.Parse(token.NextToken());
                                    int airW = 0;
                                    int[] airWs = new int[0];
                                    int airH = 0;
                                    int airM = 0;
                                    if (running)
                                    {
                                        if (v == 1)
                                            airW = int.Parse(token.NextToken());
                                        else
                                        {
                                            string[] r = token.NextToken().Split('|');
                                            airWs = new int[r.Length];
                                            for (int i = 0; i < r.Length; ++i)
                                                airWs[i] = int.Parse(r[i]);
                                        }
                                        airH = int.Parse(token.NextToken());
                                        airM = int.Parse(token.NextToken());
                                    }
                                    string network = token.NextToken();
                                    string networkU = token.NextToken();
                                    string[] genres = token.NextToken().Split('|');
                                    if (v == 1)
                                        rage = new TvRageEntry(tvRageId, "", "", genres, running, network, networkU, airW, airH, airM);
                                    else
                                    {
                                        string rt = token.NextToken();
                                        int runtime = int.Parse(rt);
                                        if (v == 2)
                                            rage = new TvRageEntry(tvRageId, "", "", genres, running, network, networkU, airWs, airH, airM, runtime);
                                        else
                                        {
                                            int lastAiredSeason = int.Parse(token.NextToken());
                                            int lastAiredEpisode = int.Parse(token.NextToken());
                                            string[] rl = token.NextToken().Split('|');
                                            int[] lastAiredDate = new int[rl.Length];
                                            for (int i = 0; i < rl.Length; ++i)
                                                lastAiredDate[i] = int.Parse(rl[i]);
                                            int nextAiredSeason = int.Parse(token.NextToken());
                                            int nextAiredEpisode = int.Parse(token.NextToken());
                                            string[] rn = token.NextToken().Split('|');
                                            int[] nextAiredDate = new int[rn.Length];
                                            for (int i = 0; i < rn.Length; ++i)
                                                nextAiredDate[i] = int.Parse(rn[i]);
                                            rage = new TvRageEntry(tvRageId, "", "", genres, running, network, networkU, airWs, airH, airM, runtime,lastAiredSeason,lastAiredEpisode,lastAiredDate,nextAiredSeason,nextAiredEpisode,nextAiredDate);
                                        }
                                    }
                                }
                            }
                        }


                        if (v == 0)
                            result.Add(new TVShowInfo(id, name, lastSeasonViewed, lastEpisodViewed, epGuideId, epGuideLoaded, imdbId, tvRageId));


                        if (v >= 1)
                            result.Add(new TVShowInfo(id, name, lastSeasonViewed, lastEpisodViewed, epGuideId, epGuideLoaded, imdbId, rage));
                    }
                }
                sr.Close();
            }
            return result;
        }
        private static StringBuilder sb;
        private static void ap(object s)
        {
            if (s == null) s = "";
            sb.Append(s.ToString() + ";");
        }
        public static void SaveFavShows(IEnumerable items)
        {
            int line = 0;
            const int version = 3;
            line = 1;
            StreamWriter sw = new StreamWriter(filename);
            try
            {
                sw.AutoFlush = true;
                foreach (TVShowInfo ts in items)
                {
                    line = 2;
                    sb = new StringBuilder();
                    ap(newBeginning);
                    ap(version);
                    line = 3;

                    //Old stuff
                    ap(ts.Id);
                    ap(ts.Name);
                    ap(ts.LastSeasonViewed);
                    ap(ts.LastEpisodViewed);
                    ap(ts.EpGuideId);
                    ap(ts.EpGuideLoaded);
                    if (ts.EpGuideLoaded)
                    {
                        ap(ts.ImdbId);
                        ap(ts.TvRageId);
                    }

                    if (ts.EpGuideLoaded && ts.EpGuideId != TVShowInfo.NO_EPGUIDE)
                    {
                        line = 4;
                        ap(ts.TvRage != null && ts.TvRage.Loaded && !ts.TvRage.Broken);
                        if (ts.TvRage != null && ts.TvRage.Loaded && !ts.TvRage.Broken)
                        {
                            ap(ts.TvRage.RunningShow);
                            if (ts.TvRage.RunningShow)
                            {
                                ap(ts.TvRage.MarshallWeekDays);
                                ap(ts.TvRage.AirHour);
                                ap(ts.TvRage.AirMin);
                            }
                            ap(ts.TvRage.Network);
                            ap(ts.TvRage.NetworkURL);
                            ap(ts.TvRage.MarshallGenres);
                            ap(ts.TvRage.Runtime);

                            ap(ts.TvRage.LastAiredSeason);
                            ap(ts.TvRage.LastAiredEpisode);
                            ap(String.Format("{0:yyyy}|{0:MM}|{0:dd}", ts.TvRage.LastAiredDate));

                            ap(ts.TvRage.NextAiredSeason);
                            ap(ts.TvRage.NextAiredEpisode);
                            ap(String.Format("{0:yyyy}|{0:MM}|{0:dd}", ts.TvRage.NextAiredDate));

                        }
                    }
                    line = 5;

                    sw.WriteLine(sb.ToString());
                    line = 6;
                }
            }
            catch(Exception e)
            {
                MessageBox.Show(line + Environment.NewLine + e.StackTrace, e.ToString());
            }
            finally
            {
                sw.Close();
            }
                line.ToString();
        }
    }
}
